<?php
/**
 * Created by PhpStorm.
 * User: chenishr
 * Date: 2018/5/26
 * Time: 3:13 PM
 */
namespace app\index\command\socket;


use chenishr\tp_swoole\WebsocketServer;
use think\Cache;
use think\Config;
use think\Exception;
use think\Log;
use think\Db;

class WebSocket extends WebsocketServer
{
    protected $userList = "UserOnlineList";
    protected $roomName = "defaultRoom";
    protected $roomListName = "RoomList";
    protected $error;
    protected $cache = true;

    protected $tm = [];

    private $redis = null;
    private $queryKey = 'comments_fetch_result_list_ley_';

    protected function initialize(\swoole_websocket_server $server)
    {
        $this->redis = new \Redis;
        $this->redis->connect(config('redis.host'), config('redis.port'));

        //创建内存表
        $this->createTable();
    }

    protected function onOpen(\swoole_websocket_server $server, \swoole_http_request $request)
    {
        $this->table->set($request->fd, [$request->fd]);
        echo "server: success with fd{$request->fd}\n";

        $msg = [
            'msgType' => 'init',
            'data' => $request->fd,
        ];
        $server->push($request->fd,json_encode($msg));

        $this->tick(1000, function($tm) use ($request){
            // 记录定时器 ID
            $this->tm[$request->fd] = $tm;
            //echo $request->fd . "\n";

            // 有数据则推送到前端
            $queryKey = $this->queryKey . $request->fd;
            while ($data = $this->redis->rpop($queryKey)){
                $msg = [
                    'msgType' => 'msg',
                    'data' => json_decode($data,true),
                ];
                $this->push($request->fd,json_encode($msg));
            }
        });

    }

    protected function onClose(\swoole_websocket_server $server, $fd)
    {
        $this->table->del($fd);
        $server->close($fd);
        print_r($this->tm);
        if('' != $this->tm[$fd]){
            $this->clearTimer($this->tm[$fd]);
            unset($this->tm[$fd]);
        }
        echo "client {$fd} closed\n";
    }

    protected function onMessage(\swoole_websocket_server $server, \swoole_websocket_frame $frame)
    {
        try {
            $server->push($frame->fd,'message OK aa');
        } catch (Exception $e) {
            Log::error($e->getMessage());
        }
        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    }

    protected function createTable()
    {
        $this->table = new \swoole_table(1024);
        $this->table->column('fd', \swoole_table::TYPE_INT);
        $this->table->create();
    }
}
